package com.f8q8.agent.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * Android指令工具类
 */
public class AndroidUtils {

    private static final Logger log = LoggerFactory.getLogger(AndroidUtils.class);

    /**
     * 查询所有udid集合
     *
     * @return 查询当前设备连接的udid集合
     */
    public static List<String> findUdids() {
        List<String> result = new ArrayList<>();
        Process process = null;
        try {
            ProcessBuilder builder = new ProcessBuilder();
            builder.command("adb", "devices");
            process = builder.start();
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                if (StringUtils.hasText(line) && !line.contains("List")) {
                    result.add(line.replace("device", "").trim());
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            if (process != null) {
                process.destroy();
            }
        }
        return result;
    }

    /**
     * 指定手机模拟点击
     *
     * @param udid 手机唯一标识
     * @param x    手机屏幕坐标x值
     * @param y    手机屏幕坐标y值
     */
    public static void click(String udid, Integer x, Integer y) {
        try {
            ProcessBuilder processBuilder = new ProcessBuilder();
            processBuilder.command("adb", "-s", udid, "shell", "input", "tap", String.valueOf(x), String.valueOf(y));
            Process process = processBuilder.start();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    /**
     * 给指定手机输入内容
     *
     * @param udid    手机唯一标识
     * @param content 输入的内容（支持中文）
     */
    public static void input(String udid, String content) {
        try {
            ProcessBuilder processBuilder = new ProcessBuilder();
            processBuilder.command("adb", "-s", udid, "shell", "am", "broadcast", "-a", "ADB_INPUT_TEXT", "--es", "msg", "'" + content + "'");
            processBuilder.start();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    public static void changeXiaomi(String udid) {
        BufferedReader reader = null;
        try {
            // 先判断当前输入法是不是Adb输入法，如果不是，切换
            String ime = "com.sohu.inputmethod.sogou.xiaomi/.SogouIME";
            ProcessBuilder builder = new ProcessBuilder();
            builder.command("adb", "-s", udid, "shell", "settings", "get", "secure", "default_input_method");
            Process process = builder.start();
            process.waitFor(5, TimeUnit.SECONDS);
            String line;
            String currentIme = null;
            reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            while ((line = reader.readLine()) != null) {
                currentIme = line;
            }
            if (!ime.equals(currentIme)) {
                ProcessBuilder processBuilder = new ProcessBuilder();
                processBuilder.command("adb", "-s", udid, "shell", "ime", "set", ime);
                Process imeProcess = processBuilder.start();
                Thread.sleep(3000L);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException ignored) {
                }
            }
        }
    }

    /**
     * 切换输入法
     */
    public static void changeIme(String udid) {
        BufferedReader reader = null;
        try {
            // 先判断当前输入法是不是Adb输入法，如果不是，切换
            String ime = "com.android.adbkeyboard/.AdbIME";
            ProcessBuilder builder = new ProcessBuilder();
            builder.command("adb", "-s", udid, "shell", "settings", "get", "secure", "default_input_method");
            Process process = builder.start();
            process.waitFor(5, TimeUnit.SECONDS);
            String line;
            String currentIme = null;
            reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            while ((line = reader.readLine()) != null) {
                currentIme = line;
            }
            if (!ime.equals(currentIme)) {
                ProcessBuilder processBuilder = new ProcessBuilder();
                processBuilder.command("adb", "-s", udid, "shell", "ime", "set", ime);
                Process imeProcess = processBuilder.start();
                Thread.sleep(3000L);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException ignored) {
                }
            }
        }
    }

    public static void clickPower(String udid) {
        clickKey(udid, 26);
    }

    public static void clickMenu(String udid) {
        clickKey(udid, 82);
    }

    public static void clickReturn(String udid) {
        clickKey(udid, 4);
    }

    public static void clickVolAdd(String udid) {
        clickKey(udid, 24);
    }

    public static void clickVolSub(String udid) {
        clickKey(udid, 25);
    }

    public static void clickVolSilence(String udid) {
        clickKey(udid, 164);
    }

    public static void screenOn(String udid) {
        clickKey(udid, 224);
    }

    public static void screenOff(String udid) {
        clickKey(udid, 223);
    }

    public static void swipe(String udid, Integer x1, Integer y1, Integer x2, Integer y2) {
        try {
            ProcessBuilder builder = new ProcessBuilder();
            builder.command("adb", "-s", udid, "shell", "input", "swipe", String.valueOf(x1), String.valueOf(y1), String.valueOf(x2), String.valueOf(y2));
            builder.start();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    private static void clickKey(String udid, int code) {
        try {
            ProcessBuilder builder = new ProcessBuilder();
            builder.command("adb", "-s", udid, "shell", "input", "keyevent", String.valueOf(code));
            builder.start();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    public static void inputQuick(String udid, String content) {
        try {
            log.info("输入了{}", content);
            ProcessBuilder builder = new ProcessBuilder();
            builder.command("adb", "-s", udid, "shell", "input", "text", content);
            builder.start();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    /**
     * 重启指定手机
     *
     * @param udid 手机唯一标识
     */
    public static void restart(String udid) {
        try {
            ProcessBuilder builder = new ProcessBuilder();
            builder.command("adb", "-s", udid, "shell", "reboot");
            builder.start();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    /**
     * 打开指定手机手机上的指定应用
     *
     * @param udid        终端唯一标识
     * @param packageName 包名
     * @param activity    启动类
     */
    public static void startApp(String udid, String packageName, String activity) {
        try {
            ProcessBuilder builder = new ProcessBuilder();
            builder.command("adb", "-s", udid, "shell", "am", "start", "-n", packageName + "/" + activity);
            builder.start();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    /**
     * 通过包名，停止app
     *
     * @param udid        终端唯一标识
     * @param packageName 包名
     */
    public static void stopApp(String udid, String packageName) {
        try {
            ProcessBuilder builder = new ProcessBuilder();
            builder.command("adb", "-s", udid, "shell", "am", "force-stop", packageName);
            builder.start();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }
}
